//
//  LBMNetworkTools.swift
//  01-Swift网络框架封装
//
//  Created by 刘保满 on 16/5/22.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
//导入命名空间
import AFNetworking


//枚举
enum HTTPMethods: Int {
    
    case POST
    case GET
    
}

struct API {
    
    static let host = "https://api.weibo.com/"
    //加载用户的token
    static let loadAccessToken = "oauth2/access_token"
    //加载用户信息
    static let loadUserInfo = "2/users/show.json"
    //加载首页的数据
    static let loadHomedata = "2/statuses/home_timeline.json"
    //发布微博
    static let sendStatus = "2/statuses/update.json"
    
    //发布图片微博
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"
    
    
    
}

class LBMNetworkTools: AFHTTPSessionManager {
    
    //声明单例对象
    static let sharedTools: LBMNetworkTools = {
        
        let url = NSURL(string: API.host)
        
        let tools = LBMNetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    //封装GET POST 请求
    func request(method: HTTPMethods,urlstring: String,parameters: AnyObject?,finished: (responsseObject: AnyObject?, error: NSError?) -> ()) {
        
        let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> () in
            finished(responsseObject: result, error: nil)
        }
        
        let failure = { (task: NSURLSessionDataTask?, error: NSError?) -> () in
            finished(responsseObject: nil, error: error)
        }
        
        if method == .GET {
            GET(urlstring, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            POST(urlstring, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
}


//MARK:把用户认证,获取用户信息的方法进行封装
extension LBMNetworkTools {
    
    //请求用户的token
    func loadAccessToken(code: String, finished: (responsseObject: AnyObject?, error: NSError?) -> ()) {
        
        //参数
        let parameters = ["client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        request(.POST, urlstring: API.loadAccessToken, parameters: parameters, finished: finished)
        
    }
    
    //请求用户信息
    func loaduserInfo(response: [String: AnyObject], finished: (responsseObject: AnyObject?, error: NSError?) -> ()) {
        //! 表示一定有值
        let token = response["access_token"]!
        let uid = response["uid"]!
        let parameters = ["access_token": token, "uid": uid]
        request(.GET, urlstring: API.loadUserInfo, parameters: parameters, finished: finished)
    }
    
    
}

//封装一个方法,用于加载首页相关的数据
extension LBMNetworkTools {
    
    func loadHomePageData(since_id: Int64 ,max_id: Int64, finished: (responsseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = LBMUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        //请求参数
        var parameters = ["access_token": token]
        if since_id > 0 {
            //添加到参数中
            parameters["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        request(.GET, urlstring: API.loadHomedata, parameters: parameters, finished: finished)
    }
}


//发布微博
extension LBMNetworkTools {
    
    func sendStatus(status: String, images: [UIImage], finished: (responsseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = LBMUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        let parameters = ["access_token": token,"status": status]
        //根据图片数量判断是什么微博
        if images.count > 0 {
            let imageData = UIImagePNGRepresentation(images.first!)!
          self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formdata) in
            
            formdata.appendPartWithFileData(imageData, name: "pic", fileName: "ocococo", mimeType: "application/octet-stream")
      
            }, progress: nil, success: { (_, result) in
                finished(responsseObject: result, error: nil)
                
            }, failure: { (_, error) in
                finished(responsseObject: nil, error: error)
          })
 
        } else {
            
            request(.POST, urlstring: API.sendStatus, parameters: parameters, finished: finished)
            
        }

        
    }
    
}



























